<template>
  <!-- 预约登记表单页面 - 包含搜索、列表展示、分页和操作对话框 -->
  <div class="app-container" :key="componentKey">
    <!-- 搜索表单区域 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <!-- 预约人姓名搜索输入框 -->
      <el-form-item label="预约人姓名" prop="applicantName">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入预约人姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>

      <!-- 预约人手机号搜索输入框 -->
      <el-form-item label="预约人手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入预约人手机号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>

      <!-- 预约状态下拉选择框 -->
      <el-form-item label="预约状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择预约状态"
          clearable
          style="width: 280px"
        >
          <!-- 动态渲染状态选项，从字典数据中获取 -->
          <el-option
            v-for="dict in lekang_appoint_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 预约时间范围选择器 -->
      <el-form-item label="预约时间" style="width: 380px">
        <el-date-picker
          v-model="daterangeAppointmentTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <!-- 搜索和重置按钮 -->
      <el-form-item>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
          style="margin-left: 30px"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 预约类型按钮组 - 快速筛选不同类型的预约 -->
    <el-form-item label="" prop="appointmentType">
      <div class="appointment-type-buttons">
        <el-button
          :class="[
            'type-button',
            queryParams.appointmentType === '' ? 'active' : '',
          ]"
          @click="handleTypeChange('')"
          >全部</el-button
        >
        <el-button
          :class="[
            'type-button',
            queryParams.appointmentType === '0' ? 'active' : '',
          ]"
          @click="handleTypeChange('0')"
          >参观预约</el-button
        >
        <el-button
          :class="[
            'type-button',
            queryParams.appointmentType === '1' ? 'active' : '',
          ]"
          @click="handleTypeChange('1')"
          >探访预约</el-button
        >
      </div>
    </el-form-item>

    <!-- 操作按钮组 - 新增、修改、删除、导出等功能 -->
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:registration:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:registration:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:registration:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:registration:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <!-- 预约登记列表表格 -->
    <el-table
      v-loading="loading"
      :data="registrationList"
      @selection-change="handleSelectionChange"
    >
      <!-- 多选列 -->
      <el-table-column type="selection" width="55" align="center" />
      <!-- 主键ID列 -->
      <el-table-column label="主键ID" align="center" prop="id" width="80" />
      <!-- 预约类型列 - 使用DictTag组件显示 -->
      <el-table-column
        label="预约类型"
        align="center"
        prop="appointmentType"
        width="120"
      >
        <template #default="scope">
          <dict-tag
            :options="appointment_type"
            :value="scope.row.appointmentType"
          />
        </template>
      </el-table-column>
      <!-- 预约人姓名列 -->
      <el-table-column
        label="预约人姓名"
        align="center"
        prop="applicantName"
        width="120"
      />
      <!-- 预约人手机号列 -->
      <el-table-column
        label="预约人手机号"
        align="center"
        prop="phone"
        width="130"
      />
      <!-- 老人姓名列 - 嵌套对象属性 -->
      <el-table-column
        label="老人姓名"
        align="center"
        prop="elderly.name"
        width="120"
      />
      <!-- 预约时间列 - 使用parseTime格式化 -->
      <el-table-column
        label="预约时间"
        align="center"
        prop="appointmentTime"
        width="120"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- 创建人列 -->
      <el-table-column
        label="创建人"
        align="center"
        prop="sysUser.nickName"
        width="100"
      />
      <!-- 创建时间列 -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="120"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- 预约状态列 - 使用自定义标签显示 -->
      <el-table-column
        label="预约状态"
        align="center"
        prop="status"
        width="100"
      >
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)" effect="light">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <!-- 修改按钮 -->
          <el-button
            link
            type="primary"
            icon="Edit"
            size="small"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:registration:edit']"
            >修改</el-button
          >
          <!-- 删除按钮 -->
          <el-button
            link
            type="primary"
            icon="Delete"
            size="small"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:registration:remove']"
            >删除</el-button
          >
          <!-- 到院按钮 -->
          <el-button
            link
            type="primary"
            size="small"
            :disabled="!isArrivalButtonEnabled(scope.row.status)"
            @click="handleArrival(scope.row)"
          >
            到院
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约登记对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="registrationRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 预约类型选择器 -->
        <el-form-item label="预约类型" prop="appointmentType">
          <el-select
            v-model="form.appointmentType"
            placeholder="请选择预约类型"
          >
            <el-option
              v-for="dict in appointment_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 微信登录账号外键 -->
        <el-form-item label="微信登录账号外键" prop="wxUserId">
          <el-input
            v-model="form.wxUserId"
            placeholder="请输入微信登录账号外键"
          />
        </el-form-item>
        <!-- 预约人姓名 -->
        <el-form-item label="预约人姓名" prop="applicantName">
          <el-input
            v-model="form.applicantName"
            placeholder="请输入预约人姓名"
          />
        </el-form-item>
        <!-- 预约人手机号 -->
        <el-form-item label="预约人手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入预约人手机号" />
        </el-form-item>
        <!-- 老人外键编号 -->
        <el-form-item label="老人外键编号" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键编号" />
        </el-form-item>
        <!-- 预约时间选择器 -->
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
            clearable
            v-model="form.appointmentTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预约时间"
          >
          </el-date-picker>
        </el-form-item>
        <!-- 创建人 -->
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <!-- 预约状态单选组 -->
        <el-form-item label="预约状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in lekang_appoint_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 到院时间选择器 -->
        <el-form-item label="到院时间" prop="arrivalTime">
          <el-date-picker
            clearable
            v-model="form.arrivalTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择到院时间"
          >
          </el-date-picker>
        </el-form-item>
        <!-- 逻辑删除 -->
        <el-form-item label="逻辑删除" prop="isDeleted">
          <el-input v-model="form.isDeleted" placeholder="请输入逻辑删除" />
        </el-form-item>
        <!-- 额外字段1 -->
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <!-- 额外字段2 -->
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <!-- 对话框页脚按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 确认到院时间弹窗 -->
    <el-dialog
      title="确认到院时间"
      v-model="arrivalDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form
        ref="arrivalFormRef"
        :model="arrivalForm"
        :rules="arrivalRules"
        label-width="80px"
      >
        <!-- 来访时间输入 -->
        <el-form-item label="来访时间" prop="arrivalTime" required>
          <el-date-picker
            v-model="arrivalForm.arrivalTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm"
            placeholder="请选择来访时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <!-- 弹窗页脚按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="confirmArrival">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Registration">
import {
  ref,
  reactive,
  onMounted,
  onActivated,
  onBeforeUnmount,
  watch,
  toRefs,
  getCurrentInstance,
} from "vue";
import { parseTime } from "@/utils/date";
import DictTag from "@/components/DictTag";
import Pagination from "@/components/Pagination";
import {
  listRegistration,
  getRegistration,
  delRegistration,
  addRegistration,
  updateRegistration,
} from "@/api/system/registration";
import { addVisitor_registration } from "@/api/system/visitor_registration";
const { proxy } = getCurrentInstance();
const { appointment_type, lekang_appoint_status } = proxy.useDict(
  "appointment_type",
  "lekang_appoint_status"
);

const registrationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAppointmentTime = ref([]);
const queryRef = ref(null);
const registrationRef = ref(null);
// 组件唯一标识，用于强制重新渲染
const componentKey = ref(Date.now());

// 到院相关数据
const arrivalDialogVisible = ref(false);
const arrivalFormRef = ref();
const currentRow = ref(null);
const arrivalForm = reactive({
  arrivalTime: "",
});

const arrivalRules = {
  arrivalTime: [
    { required: true, message: "来访时间不能为空", trigger: "change" },
  ],
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appointmentType: null,
    applicantName: null,
    phone: null,
    appointmentTime: null,
    status: null,
  },
  rules: {
    appointmentType: [
      { required: true, message: "预约类型不能为空", trigger: "blur" },
    ],
    applicantName: [
      { required: true, message: "预约人姓名不能为空", trigger: "blur" },
    ],
    phone: [
      { required: true, message: "预约人手机号不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询预约登记列表 */
function getList() {
  loading.value = true;
  // 直接使用原始响应式对象
  data.queryParams.params = {};
  if (
    daterangeAppointmentTime.value &&
    daterangeAppointmentTime.value.length === 2
  ) {
    data.queryParams.params["beginAppointmentTime"] =
      daterangeAppointmentTime.value[0];
    data.queryParams.params["endAppointmentTime"] =
      daterangeAppointmentTime.value[1];
  }
  listRegistration(data.queryParams).then((response) => {
    registrationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取状态标签类型 - 根据图片中的字典数据修正 */
function getStatusTagType(status) {
  const statusMap = {
    0: "info", // 已取消 - 灰色
    1: "success", // 已完成 - 绿色
    2: "warning", // 待上门 - 黄色
    3: "danger", // 已过期 - 红色
  };
  return statusMap[status] || "info";
}

/** 获取状态显示文本 */
function getStatusLabel(status) {
  const statusDict = lekang_appoint_status.value.find(
    (item) => item.value === status
  );
  return statusDict ? statusDict.label : status;
}

/** 判断到院按钮是否可用 - 根据图片中的字典数据修正 */
function isArrivalButtonEnabled(status) {
  // 待上门(2)、已过期(3) 状态可点击
  return status === "2" || status === "3";
}

/** 处理到院操作 */
function handleArrival(row) {
  currentRow.value = row;
  arrivalForm.arrivalTime = "";
  arrivalDialogVisible.value = true;
}

/** 取消按钮处理 */
function handleCancel() {
  arrivalDialogVisible.value = false;
  // 重置表单
  if (arrivalFormRef.value) {
    arrivalFormRef.value.resetFields();
  }
}

/** 确认到院 */
function confirmArrival() {
  arrivalFormRef.value.validate((valid) => {
    if (valid && currentRow.value) {
      // 格式化时间为ISO标准格式
      const formatToISODate = (dateString) => {
        if (!dateString) return "";
        const date = new Date(dateString);
        return date.toISOString(); // 转换为 "2025-10-14T10:21:29.000Z"
      };

      const updateData = {
        id: currentRow.value.id,
        status: "1", // 1=已完成
        arrivalTime: formatToISODate(arrivalForm.arrivalTime),
      };

      // 先更新预约登记状态
      updateRegistration(updateData)
        .then(() => {
          const visitorData = {
            // 将预约类型映射为来访类型：0=参观来访，1=探访来访
            visitorType:
              currentRow.value.appointmentType === "0"
                ? "参观来访"
                : "探访来访",
            visitorName: currentRow.value.applicantName, // 来访人姓名
            phone: currentRow.value.phone, // 手机号
            elderlyId: currentRow.value.elderlyId, // 老人外键编号
            visitTime: arrivalForm.arrivalTime, // 来访时间
            status: "1", // 默认设置为有效状态
            // 创建人信息由后端自动填充
            creator: currentRow.value.creator,
            extraField1: `预约ID:${currentRow.value.id}`, // 记录关联的预约ID
          };

          // 准备提交来访登记数据

          // 调用来访登记API
          return addVisitor_registration(visitorData);
        })
        .then(() => {
          proxy.$modal.msgSuccess("到院确认成功，已同步到来访登记");
          arrivalDialogVisible.value = false;
          getList();
        })
        .catch((error) => {
          console.error("到院确认或来访登记失败:", error);
          proxy.$modal.msgError("操作失败，请重试");
        });
    }
  });
}

/** 预约类型按钮点击事件 */
function handleTypeChange(type) {
  // 直接修改原始响应式对象的属性，确保响应性正确触发
  data.queryParams.appointmentType = type;
  handleQuery();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    appointmentType: null,
    wxUserId: null,
    applicantName: null,
    phone: null,
    elderlyId: null,
    appointmentTime: null,
    creator: null,
    createTime: null,
    status: null,
    arrivalTime: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("registrationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  // 直接修改原始响应式对象的属性
  data.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeAppointmentTime.value = [];
  // 直接修改原始响应式对象的属性
  data.queryParams.appointmentType = null;
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预约登记";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getRegistration(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改预约登记";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["registrationRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        // 修改操作
        updateRegistration(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 新增操作
        addRegistration(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除预约登记编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delRegistration(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/registration/export",
    {
      ...queryParams.value,
    },
    `registration_${new Date().getTime()}.xlsx`
  );
}

// 重置组件状态函数
function resetComponentState() {
  // 重置所有响应式数据
  registrationList.value = [];
  loading.value = true;
  total.value = 0;
  data.queryParams.pageNum = 1;
  daterangeAppointmentTime.value = [];
  // 更新组件key，强制Vue重新创建组件实例
  componentKey.value = Date.now();
}

// 使用onMounted钩子确保组件完全挂载后再加载数据
onMounted(() => {
  resetComponentState();
  getList();
});

// 添加onActivated钩子确保每次进入页面（包括从缓存中恢复）都重新加载数据
onActivated(() => {
  resetComponentState();
  getList();
});

// 添加onBeforeUnmount钩子在组件卸载前清理状态
onBeforeUnmount(() => {
  resetComponentState();
});
</script>

<style scoped>
/* 预约类型按钮样式 */
.appointment-type-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.type-button {
  min-width: 100px;
  font-size: 14px;
  color: #606266;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
  border-radius: 3px;
}

.type-button:hover {
  color: #409eff;
  background-color: #ecf5ff;
  border-color: #c6e2ff;
}

.type-button.active {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
}

.type-button.active:hover {
  color: #fff;
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 操作按钮样式 */
.el-button.is-disabled {
  color: #c0c4cc !important;
  cursor: not-allowed;
}

/* 表格样式优化 */
.el-table {
  margin-top: 16px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

/* 状态标签样式 */
.el-tag {
  font-weight: 500;
}

/* 操作列按钮间距 */
.small-padding .el-button {
  margin: 0 2px;
}
</style>